package com.cwg.dict.stem.service.impl;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.edu.ynu.sei.dict.service.core.IDictQueryService;
import cn.edu.ynu.sei.dict.service.core.Word;

import com.cwg.dict.exception.DictionaryNotFoundException;
import com.cwg.dict.exception.WordNotFoundException;
import com.cwg.dict.stem.service.Translator;

public class TranslatorImpl implements Translator {

	private Logger				logger	= LoggerFactory.getLogger(TranslatorImpl.class);
	private IDictQueryService	stardictReader;

	public IDictQueryService getStardictReader() {
		return stardictReader;
	}

	public void setStardictReader(IDictQueryService stardictReader) {
		this.stardictReader = stardictReader;
	}

	@Override
	public String toChinese(String input) {
		try {
			Word lookup = stardictReader.lookup(input);
			verifyDictionary(lookup.defComeFrom);
			String result = StringUtils.substringBefore(lookup.definition, "相關詞組").replace("\n", ";");
			logger.info("{} tranlate as -> {}", input, result);
			return result;
		} catch (WordNotFoundException e) {
			logger.warn("the word [{}] not found", input);
			return input;
		}
	}

	/**
	 * NOTE: this substring method is only can apply to langdao dictionary (file name : langdao-ec-big5);
	 */
	private void verifyDictionary(String dicName) {
		logger.debug("using dictionary [{}]", dicName);
		if (!StringUtils.contains(dicName, "朗道英漢字典")) {
			String errorMsg = "this program only can ues the 朗道英漢字典5.0(stardict-langdao-ec-big5-version xxx";
			try {
				throw new DictionaryNotFoundException(errorMsg);
			} catch (DictionaryNotFoundException e) {
				logger.error(errorMsg);
				e.printStackTrace();
			}
		}
	}
}
